<!--
 * @Author: LiYuan
 * @Date: 2021-04-01 09:42:49
 * @LastEditTime: 2021-07-02 10:37:19
 * @LastEditors: lily
 * @Description: 添加备注
 * You build it, You run it.
-->

<template>
  <base-modal :title="$t('common.base.addRemark')" :show.sync="visible" :width="dialogWidth" class="event-add-remarks-dialog">
    <div class="base-modal-content">
      <el-form label-position="top" v-model="addRemarkForm" ref="addRemarkRef" :rules="rules">
        <template v-if="isHasAmerPrint">
          <el-form-item :label="$t('common.base.content')">
            <form-richtext
              ref="richTextRef"
              :value="addRemarkForm.updateContent"
              :hiddenBoldEnable="true"
              @input="toUpdateContent"
            />
          </el-form-item>
          <el-form-item :label="$t('event.detail.remarkUpdateUser')" prop="updateUsers">
            <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="addRemarkForm.updateUsers" :at-users.sync="atUsers" direction="bottom">
              <template slot="item" slot-scope="item">
                <img :src="head(item.user.head)">
                <span>{{item.user.displayName}}</span>
              </template>
              <textarea ref="editor" class="base-at-textarea" @input="toUpdateUser" :placeholder="$t('common.base.pleaseSelect')" maxlength="500" :rows="2"></textarea>
            </biz-at-textarea>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="$t('common.base.content')" prop="updateContent">
            <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="addRemarkForm.updateContent" :at-users.sync="atUsers" direction="bottom">
              <template slot="item" slot-scope="item">
                <img :src="head(item.user.head)">
                <span>{{item.user.displayName}}</span>
              </template>
              <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="$t('event.detail.components.dialog.text20')" maxlength="500" :rows="6"></textarea>
            </biz-at-textarea>
          </el-form-item>
        </template>
        <!-- 内容模版 -->
        <el-form-item v-if="messageConfig.eventRemark">
          <el-select 
            v-model="addRemarkForm.remarkSelect" 
            @change="remarkSelectedChange"
            :placeholder="remarkList.length > 0 ? $t('event.detail.components.dialog.text18') : $t('event.detail.components.dialog.text19')"
            style="width: 100%"
          >
            <el-option
              v-for="item in remarkList"
              :key="item.id"
              :label="item.content"
              :value="item.content">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.attachment')" prop="attachments">
          <base-upload :value="addRemarkForm.attachments" @input="upload" @remove="remove" formEditingMode="create"></base-upload>
        </el-form-item>
      </el-form>

      <el-checkbox-group v-model="addRemarkForm.visibleAuth">
        <el-checkbox label="showInOwn" :disabled="showInOwnDisabled">
          {{$t('common.option.commentAction.0')}}
          <el-tooltip class="item" effect="dark" :content="$t('event.detail.components.dialog.text21')" placement="bottom">
            <i class="iconfont icon-warning-circle-fill"></i>
          </el-tooltip>
        </el-checkbox>

        <el-checkbox label="toCustomer" :disabled="toCustomerDisabled" @change="toCustomerChangeHandler">
          {{$t('common.option.commentAction.1')}}
          <el-tooltip class="item" effect="dark" :content="$t('event.detail.components.dialog.text22')" placement="bottom">
            <i class="iconfont icon-warning-circle-fill"></i>
          </el-tooltip>
        </el-checkbox>
        <!-- 亚玛芬不显示 -->
        <template v-if="!isHasAmerPrint">
          <el-checkbox label="cusNotice" :disabled="cusNoticeDisabled" @change="cusNoticeChangeHandler">
            {{$t('event.detail.components.dialog.text17')}}
            <el-tooltip class="item" effect="dark" :content="$t('event.detail.components.dialog.text23')" placement="bottom">
              <i class="iconfont icon-warning-circle-fill"></i>
            </el-tooltip>
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>
    <div slot="footer">
      <el-button @click="visible = false">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="pending">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { getRootWindow } from '@src/util/dom';
import * as EventApi from '@src/api/EventApi.js';
import { parse } from '@src/util/querystring';
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import {enCodeAtText, getReceivers} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';

export default {
  name: 'event-add-remarks-dialog',
  props:{
    workEvent: {
      type: Object,
      default: () => {
        return {}
      }
    },
    messageConfig: {
      type: Object,
      default: () => {
        return {
          eventRemark: false
        }
      }
    },
    remarkList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    // 亚马芬灰度
    isHasAmerPrint() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.AMER_PRINT ?? false;
    },
    dialogWidth() {
      return this.isHasAmerPrint ? '700px' : '600px'
    }
  },
  watch: {
    'addRemarkForm.visibleAuth'(val) {
      this.toCustomerDisabled = val.indexOf('showInOwn') >= 0
      this.cusNoticeDisabled = val.indexOf('showInOwn') >= 0
      this.showInOwnDisabled = val.indexOf('toCustomer') >= 0 ? true : val.indexOf('cusNotice') >= 0
    }
  },
  data: () => {
    return {
      pending: false,
      rules: {},
      addRemarkForm: {
        visibleAuth: [],
        updateContent: '',
        updateUsers: '',
      },
      visible: false,
      showInOwnDisabled: false,
      toCustomerDisabled: false,
      cusNoticeDisabled: false,
      atUsers:[]
    }
  },
  methods: {
    openDialog() {
      this.visible = true;
    },
    handleConfirm() {
      const users = this.isHasAmerPrint ? this.addRemarkForm.updateUsers :  this.addRemarkForm.updateContent

      if (this.addRemarkForm.updateContent || (this.isHasAmerPrint && this.addRemarkForm.updateUsers)) {
        let updateContent = this.addRemarkForm.updateContent
        let receivers = ''
        let query = ''
        if(this.addRemarkForm.visibleAuth.indexOf('showInOwn') == -1){
          !this.isHasAmerPrint &&( updateContent = enCodeAtText(updateContent, this.atUsers));
          receivers = getReceivers(users, this.atUsers)
          let queryData = {
            receivers,
            tenantId: useTenantId().value,
            content: cutAtTextContent(users),
            sendUserName: useRootUser().value?.displayName,
            bizId: this.workEvent.id,
            bizNo: this.workEvent.eventNo,
          };
          query = '?';
          for (let i in queryData) {
            query += `&${i}=${queryData[i]}`;
          }
        }
        
        let form = {
          content: {
            updateContent: updateContent,
            updateType: 'eRecord'
          },
          eventId: this.workEvent.id,
          eventNo: this.workEvent.eventNo
        }
        
        if(this.addRemarkForm.attachments && this.addRemarkForm.attachments.length > 0) {
          form.attachments = this.addRemarkForm.attachments.slice()
        }

        // 需要修改下：updateContent存储富文本的内容，updateUser存储@人员的信息
        if(this.isHasAmerPrint) {
          form.content.updateUser = enCodeAtText(this.addRemarkForm.updateUsers, this.atUsers)
        }
        if(this.addRemarkForm.visibleAuth) {
          this.addRemarkForm.visibleAuth.forEach(item => {
            form[item] = 1
          })
        }

        this.pending = true
        EventApi.eventCreateRecord(form, query)
          .then(res => {
            if (res.status == 0) {
              window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`;
            } else {
              this.pending = false
              this.$message.error(res.message);
            }
          })
      }else{
        this.$message.warning(this.$t('common.placeholder.inputContent'));
      } 
      
    },

    // 上传
    upload(queue){
      this.$set(this.addRemarkForm, 'attachments', queue)
    },

    // 移除上传
    async remove(file){
      if(!await this.$platform.confirm(this.$t('common.form.preview.file.deleteFileTips'))) return;

      let index = -1;
      for(let i = 0; i < this.addRemarkForm.attachments.length; i++){
        let f = this.addRemarkForm.attachments[i];
        if(f.url == file.url){
          index = i;
          break;
        }
      }
      if(index >= 0) this.addRemarkForm.attachments.splice(index, 1);
    },

    remarkSelectedChange(value) {
      if(this.addRemarkForm.updateContent) {
        this.$confirm(this.$t('common.base.tip.replaceCommentConfirm'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.makeSure'),
          type: 'warning',
        })
          .then(() => {
            this.addRemarkForm.updateContent = value
          })
      } else {
        this.addRemarkForm.updateContent = value
      }
    },

    toCustomerChangeHandler(val) {
      if(!val) {
        this.addRemarkForm.visibleAuth = []
      }
    },

    cusNoticeChangeHandler(val) {
      if(val) {
        this.addRemarkForm.visibleAuth.push('toCustomer')
      }
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    inputContent(event){
      let value = event.target.value;
      this.addRemarkForm.updateContent = value;
    },
    // 亚玛芬定制-更新@人员
    toUpdateUser(event){
      this.addRemarkForm.updateUsers = event.target.value;
    },
    // 亚玛芬定制-更新富文本内容
    toUpdateContent(value) {
      // 移除<strong>
      let filteredContent = value.replace(/<strong>/g, '<span>');
      filteredContent = filteredContent.replace(/<\/strong>/g, '</span>');
      this.addRemarkForm.updateContent = filteredContent
    },
  }
}
</script>

<style lang="scss" scoped>
.base-modal-content {
  padding: 20px;
}
.el-radio-group {
  label {
    margin-right: 20px;
    i {
      vertical-align: text-bottom;
    }
  }
}
</style>